package researchgrants.parts.GrantRequest;

import java.awt.Window;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import researchgrants.parts.db.Db;

/*
 * This class is a container for statically managing the list of all grants
 * Any public interaction with grants should come through this class.
 * Getting, viewing, adding, deleting, and all grants related activity should be proxied through here, either directly by a method or indirectly by recieving a GrantRequest object.
 */
public class AllGrantRequests {

    static private GrantRequestsList allGrantRequests;
    static {
        allGrantRequests=new GrantRequestsList();
        try {
            Connection conn=Db.openDbConnection();
            PreparedStatement prepareStatement = Db.createPreparedStatement(conn, "SELECT GrantRequestID FROM tblGrantRequests");
            ResultSet grantRequestsRs = prepareStatement.executeQuery();
            while (grantRequestsRs.next()) {
                int grantRequestId=(Integer)Db.getColumn(grantRequestsRs,1);
                allGrantRequests.add(GrantRequest.getById(grantRequestId));
            }
            grantRequestsRs.close();
            prepareStatement.close();
            Db.closeDbConnection(conn);
        } catch (SQLException ex) {
            Logger.getLogger(AllGrantRequests.class.getName()).log(Level.SEVERE, "Could not load all grant requests", ex);
        } catch (Exception ex) {
            Logger.getLogger(AllGrantRequests.class.getName()).log(Level.SEVERE, "Could not load all grant requests", ex);
        }
    }
    
    // creates a new grant request and updates the global manager of grant requests
    public static GrantRequest inputNewGrantRequest(Window parent) {
        GrantRequest newGrantRequest=GrantRequest.inputNew(parent);
        if (newGrantRequest!=null) {
            allGrantRequests.add(newGrantRequest);
        }
        return(newGrantRequest);
    }


    // This is the starting list of grant requests.
    // Through this list, other parts of the software can retreive single or multiple grant requests.
    public static GrantRequestsList getAllGrantRequests() {
        GrantRequestsList res=null;
        try {
            res= (GrantRequestsList) allGrantRequests.clone();
        } catch (CloneNotSupportedException ex) {
            Logger.getLogger(AllGrantRequests.class.getName()).log(Level.SEVERE, null, ex);
        }
        return(res);
    }
}
